<template>
  <div>
    <h2>我的课程</h2>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item to="/MemberMain">主页</el-breadcrumb-item>
      <el-breadcrumb-item>我的课程</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card style="margin-top: 20px;">
      <el-table :data="tableData" style="width: 100%;" v-loading="loading">
        <el-table-column prop="classId" label="编号" />
        <el-table-column prop="className" label="名称" />
        <el-table-column prop="classBegin" label="时间" />
        <el-table-column prop="coach" label="教练" />
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button type="danger" size="small" @click="onDelete(scope.row)">退课</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { useRouter } from 'vue-router'

const router = useRouter()
const tableData = ref([])
const loading = ref(false)

// 模拟未登录错误码，可替换成真实 CodeEnum 引用
const NOT_LOGIN_CODE = 620

// 加载用户课程数据
const loadData = () => {
  loading.value = true
  axios.get('/server/member/findByMemberAccount', {
    headers: {
      'Authorization': localStorage.getItem('token')
    }
  })
      .then(res => {
        if (res.data.code === 200) {
          tableData.value = res.data.data.map(item => ({
            ...item,
            classOrderId: item.id || item.classOrderId
          }))
        } else if (res.data.code === NOT_LOGIN_CODE) {
          ElMessage.error('请先登录')
          router.push('/MemberLogin')
        } else {
          ElMessage.error('获取数据失败: ' + (res.data.message || '未知错误'))
        }
      })
      .catch(error => {
        console.error('获取课程数据失败：', error)
        ElMessage.error('加载课程数据失败')
      })
      .finally(() => {
        loading.value = false
      })
}

// 页面初始化加载
onMounted(() => {
  if (!localStorage.getItem('token')) {
    ElMessage.error('请先登录')
    router.push('/MemberLogin')
    return
  }
  loadData()
})

// 退课操作（改为 POST 请求）
const onDelete = (row) => {
  ElMessageBox.confirm(
      `确定要退选课程【${row.className}】吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    loading.value = true
    axios.delete('/server/member/deleteClassOrder', {
      classOrderId: row.classOrderId
    }, {
      headers: {
        'Authorization': localStorage.getItem('token')
      },
      withCredentials: true
    })
        .then(response => {
          if (response.data.code === 200) {
            ElMessage.success('退课成功')
            loadData()
          } else if (response.data.code === NOT_LOGIN_CODE) {
            ElMessage.error('请先登录')
            router.push('/MemberLogin')
          } else {
            ElMessage.error('退课失败: ' + (response.data.message || '未知错误'))
          }
        })
        .catch(error => {
          console.error('退课失败:', error)
          ElMessage.error('请求失败，无法退课')
        })
        .finally(() => {
          loading.value = false
        })
  }).catch(() => {
    ElMessage.info('已取消退课')
  })
}
</script>

<style scoped>
h2 {
  margin-bottom: 10px;
}
</style>
